<template>
  <div class="user-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增用户
          </el-button>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="用户名">
            <el-input 
              v-model="searchForm.username" 
              placeholder="请输入用户名" 
              clearable
            />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input 
              v-model="searchForm.email" 
              placeholder="请输入邮箱" 
              clearable
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table :data="tableData" v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="roles" label="角色">
          <template #default="{ row }">
            <el-tag 
              v-for="role in row.roles" 
              :key="role" 
              size="small" 
              style="margin-right: 5px;"
            >
              {{ role }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-switch 
              v-model="row.status" 
              :active-value="1" 
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="warning" link @click="handleResetPassword(row)">
              <el-icon><Key /></el-icon>
              重置密码
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单弹窗 -->
    <UserForm 
      v-model="formVisible" 
      :user-data="currentUser" 
      @success="handleFormSuccess" 
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Edit, Delete, Key } from '@element-plus/icons-vue'
import UserForm from './UserForm.vue'

// 响应式数据
const loading = ref(false)
const formVisible = ref(false)
const currentUser = ref(null)

const searchForm = reactive({
  username: '',
  email: '',
  status: ''
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const tableData = ref([])

// 方法
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

const handleAdd = () => {
  currentUser.value = null
  formVisible.value = true
}

const handleEdit = (row) => {
  currentUser.value = { ...row }
  formVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确认删除用户 "${row.username}" 吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 这里调用删除API
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    // 用户取消删除
  }
}

const handleStatusChange = async (row) => {
  try {
    // 这里调用状态更新API
    ElMessage.success(`用户状态已${row.status ? '启用' : '禁用'}`)
  } catch (error) {
    // 恢复状态
    row.status = row.status ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

const handleResetPassword = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确认重置用户 "${row.username}" 的密码吗？`,
      '确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 这里调用重置密码API
    ElMessage.success('密码重置成功，新密码已发送至用户邮箱')
  } catch (error) {
    // 用户取消
  }
}

const handleSizeChange = (val) => {
  pagination.size = val
  pagination.current = 1
  loadData()
}

const handleCurrentChange = (val) => {
  pagination.current = val
  loadData()
}

const handleFormSuccess = () => {
  formVisible.value = false
  loadData()
}

const loadData = async () => {
  loading.value = true
  try {
    // 这里调用API获取数据
    // const response = await userApi.getUsers({
    //   ...searchForm,
    //   page: pagination.current,
    //   size: pagination.size
    // })
    
    // 模拟数据
    setTimeout(() => {
      tableData.value = [
        {
          id: 1,
          username: 'admin',
          email: 'admin@example.com',
          roles: ['管理员'],
          status: 1,
          createTime: '2024-01-01 00:00:00'
        },
        {
          id: 2,
          username: 'user',
          email: 'user@example.com',
          roles: ['普通用户'],
          status: 1,
          createTime: '2024-01-02 00:00:00'
        }
      ]
      pagination.total = 2
      loading.value = false
    }, 500)
  } catch (error) {
    ElMessage.error('数据加载失败')
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.user-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
